<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\api;

use App\Common\Repositories\System\CustomerAdminRepository;
use App\Exception\AppException;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Crontab\Annotation\Crontab;
use Psr\Http\Message\ResponseInterface;
use xsl\basic\BaseController;

class Auth extends BaseController
{
   // #[Crontab(rule: "*/5 * * * * *", memo: "test")]
    public function test()
    {
        go(function () {
            $i = 0;
            while (true) {
                Coroutine::sleep(0.1);
                echo "📝 Do something...\n";
                if (++$i === 5) {
                    echo "🛎 Done\n";
                    break;
                }
            }
            echo "🎉 All right!\n";
        });
    }

    public function login(): ResponseInterface
    {
        try {
            $customerAdminRepository = \Hyperf\Support\make(CustomerAdminRepository::class);
            $params = $this->request->all();
            $token = $customerAdminRepository->attempt($params, $this->request);
            return $this->success(['token' => $token]);
        } catch (AppException $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function logout(): ResponseInterface
    {
        if ($this->request->isLogin()){
            $customerAdminRepository = \Hyperf\Support\make(CustomerAdminRepository::class);
            $customerAdminRepository->clearToken($this->request->token());
        }
        return $this->success();
    }
}
